#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/10 14:37
# @Author  : harry
import threading

from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from dvadmin.utils.json_response import DetailResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin_wechat.filters import FanManagementFilterSet
from dvadmin_wechat.models import FanManagement, FanTags
from dvadmin_wechat.tools import sync_fan_management, sync_tag_list, sync_black_list, sync_remark

SUBSCRIBE_SCENE = {"ADD_SCENE_SEARCH": "公众号搜索", "ADD_SCENE_ACCOUNT_MIGRATION": "公众号迁移",
                   "ADD_SCENE_PROFILE_CARD": "名片分享", "ADD_SCENE_QR_CODE": "扫描二维码", "ADD_SCENE_PROFILE_LINK": "图文页内名称点击",
                   'ADD_SCENE_PROFILE_ITEM': "图文页右上角菜单", 'ADD_SCENE_PAID': "支付后关注",
                   "ADD_SCENE_WECHAT_ADVERTISEMENT": "微信广告",
                   'ADD_SCENE_REPRINT': "他人转载", 'ADD_SCENE_LIVESTREAM': '视频号直播', 'ADD_SCENE_CHANNELS': "视频号",
                   "ADD_SCENE_OTHERS": "其他"
                   }


class FanManagementCreateSerializer(CustomModelSerializer):
    fan_tags_list = serializers.SerializerMethodField(read_only=True)
    fan_groups_name = serializers.SerializerMethodField(read_only=True)
    official_account_management_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = FanManagement
        fields = "__all__"
        read_only_fields = ["id"]

    def get_fan_tags_list(self, obj):
        return [{"name": i.name, "tagsid": i.tagsid, "id": i.id} for i in obj.fan_tags.all()]

    def get_fan_groups_name(self, obj):
        return obj.fan_groups.name

    def get_official_account_management_name(self, obj):
        return obj.official_account_management.name


class FanManagementViewSet(CustomModelViewSet):
    """
    菜粉丝管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = FanManagement.objects.filter(official_account_management__status=1)
    serializer_class = FanManagementCreateSerializer
    create_serializer_class = FanManagementCreateSerializer
    update_serializer_class = FanManagementCreateSerializer
    search_fields = ['name', 'official_account_management__name', "open_id", 'union_id', "subscribe_scene"]
    filter_class = FanManagementFilterSet

    def get_queryset(self):
        queryset = self.queryset
        fan_tags_name = self.request.query_params.get('fan_tags_name')
        if fan_tags_name:
            f_t = FanTags.objects.filter(name__icontains=fan_tags_name)
            queryset = queryset.filter(fan_tags__in=f_t)
        return queryset

    @action(methods=["GET"], detail=False, permission_classes=[IsAuthenticated])
    def sync(self, request):
        """同步粉丝信息"""
        for th in threading.enumerate():
            if th.name == "sync_management_1":
                return ErrorResponse(msg="上一次同步粉丝还未完成,请稍后再试")
        official_account_management_id = self.request.query_params.get("official_account_management_id")
        t = threading.Thread(name='sync_management_1', target=sync_fan_management,
                             kwargs={'official_account_management_id': official_account_management_id})
        t.daemon = True
        t.start()
        return DetailResponse(data=None, msg="同步成功")

    @action(methods=["POST"], detail=False, permission_classes=[IsAuthenticated])
    def black_list(self, request):
        """拉黑、取消拉黑"""
        is_black = 0 if str(request.data.get("is_black")) == '0' else 1
        openid_list = request.data.get("openid_list")

        for th in threading.enumerate():
            if th.name == "sync_management_black":
                return ErrorResponse(msg="上一次拉黑或取消拉黑,还未完成,请稍后再试")
        official_account_management_id = request.data.get("official_account_management_id")
        # 同步
        sync_black_list(official_account_management_id=official_account_management_id, is_black=is_black,
                        openid_list=openid_list)
        return DetailResponse(data=None, msg="操作成功")

    @action(methods=["POST"], detail=False, permission_classes=[IsAuthenticated])
    def tag_list(self, request):
        """打标签1 、取消标签0 操作"""
        # print(request.data)
        is_black = 0 if str(request.data.get("is_black")) == '0' else 1
        official_account_management_id = request.data.get("official_account_management_id")
        tagid_list = request.data.get("tagid_list")
        openid_list = request.data.get("openid_list")
        is_one = request.data.get("is_one")
        sync_tag_list(is_black=is_black, official_account_management_id=official_account_management_id,
                      openid_list=openid_list, tagid_list=tagid_list, is_one=is_one)
        return DetailResponse(data=None, msg="同步成功")
    @action(methods=["POST"], detail=False, permission_classes=[IsAuthenticated])
    def set_remark(self, request):
        """设置备注"""
        remark = request.data.get("remark")
        openid_list = request.data.get("openid_list")
        official_account_management_id = request.data.get("official_account_management_id")
        # 同步
        sync_remark(official_account_management_id=official_account_management_id, remark=remark,
                    openid_list=openid_list)
        return DetailResponse(data=None, msg="操作成功")
